package com.example.home.findWork.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.home.R;
import com.example.home.findWork.bean.PersonalresumeBean;
import com.example.home.findWork.bean.ProfessionBean;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;
import com.example.home.tool.RunOnUiThreadTool;
import com.google.android.material.tabs.TabLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class OnlyMeFragment extends Fragment {
    private TabLayout tabList;
    private View view;
    private LinearLayout lila1;
    private EditText mostEducation;
    private EditText education;
    private EditText address;
    private EditText experience;
    private EditText individualResume;
    private EditText money;
    private Spinner positionId;
    private TextView submit;
    private LinearLayout lila2;
    private TextView mostEducation2;
    private TextView education2;
    private TextView address2;
    private TextView experience2;
    private TextView individualResume2;
    private TextView money2;
    private TextView positionId2;
    private LinearLayout lila3;
    private EditText mostEducation3;
    private EditText education3;
    private EditText address3;
    private EditText experience3;
    private EditText individualResume3;
    private EditText money3;
    private Spinner positionId3;
    private TextView submit3;
    private HashMap<Integer, String> map;
    private PersonalresumeBean personalresumeBean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_only_me, container, false);

        initview();
        //个人简历的管理
        resumemanagement();

        addresume();

        return view;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 在这里处理广播接收逻辑
            String action = intent.getAction();
            if ("bov_action4".equals(action)) {
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        // 在 onStart 方法中注册广播接收器
        IntentFilter filter = new IntentFilter("bov_action4");
        requireActivity().registerReceiver(broadcastReceiver, filter);
    }

    @Override
    public void onStop() {
        super.onStop();
        // 在 onStop 方法中取消注册广播接收器，以避免内存泄漏
        requireActivity().unregisterReceiver(broadcastReceiver);
    }

    private void resumemanagement() {
        ArrayList<String> list = new ArrayList<>();
        list.add("新增简历");
        list.add("查看简历");
        list.add("编辑简历");
        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabList.newTab();
            tab.setText(list.get(i));
            tabList.addTab(tab);
        }


        tabList.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 0){
                    lila1.setVisibility(View.VISIBLE);
                    lila2.setVisibility(View.GONE);
                    lila3.setVisibility(View.GONE);
                    //新增简历
                    addresume();
                }else if (position == 1){
                    lila1.setVisibility(View.GONE);
                    lila2.setVisibility(View.VISIBLE);
                    lila3.setVisibility(View.GONE);
                    //查看简历
                    showresume();
                }
                else if (position == 2){
                    lila1.setVisibility(View.GONE);
                    lila2.setVisibility(View.GONE);
                    lila3.setVisibility(View.VISIBLE);
                    //修改简历
                    updataresume();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void updataresume() {
        if (personalresumeBean == null) {
            showresume();
        }

        if (personalresumeBean != null) {
            PersonalresumeBean.DataBean data = personalresumeBean.getData();
            mostEducation3.setText(data.getMostEducation());
            education3.setText(data.getEducation());
            address3.setText(data.getAddress());
            experience3.setText(data.getExperience());
            individualResume3.setText(data.getIndividualResume());
            money3.setText(data.getMoney());
        }

        Set<Integer> strings = map.keySet();
        ArrayList<String> listvalues = new ArrayList();
        for (Integer integer : strings) {
            listvalues.add(map.get(integer));
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(this.getActivity(), R.layout.item_sprnner, listvalues);
        positionId3.setAdapter(arrayAdapter);
        positionId3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Integer spnnerkey = 0;
                Set<Map.Entry<Integer, String>> entries = map.entrySet();
                for (Map.Entry<Integer, String> entry : entries) {
                    Integer key = entry.getKey();
                    String value = entry.getValue();
                    if (listvalues.get(position).equals(value)) {
                        //职位的ID
                        spnnerkey = key;
                        //点击提交修改简历
                        submitupdataresume(spnnerkey);
                    }
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void submitupdataresume(Integer spnnerkey) {
        submit3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String addresString = address3.getText().toString();
                String educationString = education3.getText().toString();
                String experienceString = experience3.getText().toString();
                String individualResumeString = individualResume3.getText().toString();
                String moneyString = money3.getText().toString();
                String mostEducationString = mostEducation3.getText().toString();


                if (!TextUtils.isEmpty(addresString) && !"".equals(addresString) &&
                        !TextUtils.isEmpty(educationString) && !"".equals(educationString) &&
                        !TextUtils.isEmpty(experienceString) && !"".equals(experienceString) &&
                        !TextUtils.isEmpty(individualResumeString) && !"".equals(individualResumeString) &&
                        !TextUtils.isEmpty(moneyString) && !"".equals(moneyString) &&
                        !TextUtils.isEmpty(mostEducationString) && !"".equals(mostEducationString)) {


                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("address", addresString);
                        jsonObject.put("education", educationString);
                        jsonObject.put("experience", experienceString);
                        jsonObject.put("individualResume", individualResumeString);
                        jsonObject.put("money", moneyString);
                        jsonObject.put("mostEducation", mostEducationString);
                        jsonObject.put("positionId", spnnerkey);
                        jsonObject.put("id", "1");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    String JSON = jsonObject.toString();
                    OKHttpTool.doNetRequest("prod-api/api/job/resume",
                            OKHttpTool.PUT,
                            GeneralClass.class,
                            new OKHttpTool.NetCallback() {
                                @Override
                                public void onSuccess(Object obj) {
                                    RunOnUiThreadTool.run(OnlyMeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                                        @Override
                                        public void set() {
                                            GeneralClass leavecommentBean = (GeneralClass) obj;
                                            if (leavecommentBean.getCode() == 200) {
                                                Toast.makeText(OnlyMeFragment.this.getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                                            } else {
                                                Toast.makeText(OnlyMeFragment.this.getActivity(), leavecommentBean.getMsg(), Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(String msg) {

                                }
                            }, JSON);
                } else {
                    Toast.makeText(OnlyMeFragment.this.getActivity(), "请填写信息", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }


    private void showresume() {
        OKHttpTool.doNetRequest("prod-api/api/job/resume/queryResumeByUserId/1",
                OKHttpTool.GET,
                PersonalresumeBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        personalresumeBean = (PersonalresumeBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PersonalresumeBean.DataBean data = personalresumeBean.getData();
                                if (personalresumeBean.getCode() == 200) {
                                    money2.setText(data.getMoney());
                                    individualResume2.setText(data.getIndividualResume());
                                    experience2.setText(data.getExperience());
                                    address2.setText(data.getAddress());
                                    education2.setText(data.getEducation());
                                    mostEducation2.setText(data.getMostEducation());

                                    Integer positionId = data.getPositionId();
                                    if (map == null) {
                                        addresume();
                                    }
                                    Set<Integer> integers = map.keySet();
                                    for (Integer integer : integers) {
                                        if (positionId == integer) {
                                            String positionString = map.get(positionId);
                                            positionId2.setText(positionString);
                                        }
                                    }

                                }
                                updataresume();
                            }
                        });
                    }


                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void addresume() {
        OKHttpTool.doNetRequest("prod-api/api/job/profession/list",
                OKHttpTool.GET,
                ProfessionBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        ProfessionBean professionBean = (ProfessionBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                map = new HashMap();
                                if (professionBean.getCode() == 200){
                                    for (int i = 0; i < professionBean.getRows().size(); i++) {
                                        ProfessionBean.RowsBean rowsBean = professionBean.getRows().get(i);
                                        map.put(rowsBean.getId(),rowsBean.getProfessionName());
                                    }
                                    spmmerresue(map);
                                }
                            }
                        });
                    }


                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void spmmerresue(HashMap<Integer, String> map) {
        Set<Integer> set = map.keySet();
        ArrayList<String> arrayList = new ArrayList<>();
        for (Integer integer: set) {
            arrayList.add(map.get(integer));
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(this.getActivity(),R.layout.item_sprnner,arrayList);
        positionId.setAdapter(arrayAdapter);
        positionId.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Integer spnkey = 0;
                Set<Map.Entry<Integer,String>> entries = map.entrySet();
                for (Map.Entry<Integer,String> entry : entries){
                    Integer key = entry.getKey();
                    String value = entry.getValue();
                    if (arrayList.get(position).equals(value)){
                        //职位的ID
                        spnkey = key;
                        //点击提交添加简历
                        submitaddresyme(spnkey);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void submitaddresyme(Integer spnkey) {
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strAddress = address.getText().toString();
                String strEducation = education.getText().toString();
                String strExperience = experience.getText().toString();
                String strIndividualResume = individualResume.getText().toString();
                String strMoney = money.getText().toString();
                String strMostEducation = mostEducation.getText().toString();
                if (!TextUtils.isEmpty(strAddress)){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("address",strAddress);
                        jsonObject.put("education",strEducation);
                        jsonObject.put("experience",strExperience);
                        jsonObject.put("individualResume",strIndividualResume);
                        jsonObject.put("money",strMoney);
                        jsonObject.put("mostEducation",strMostEducation);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    OKHttpTool.doNetRequest("prod-api/api/job/resume",
                            OKHttpTool.POST,
                            GeneralClass.class,
                            new OKHttpTool.NetCallback() {
                                @Override
                                public void onSuccess(Object obj) {
                                    GeneralClass generalClass = (GeneralClass) obj;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (generalClass.getCode() == 200) {
                                                Toast.makeText(OnlyMeFragment.this.getActivity(), "提交成功", Toast.LENGTH_SHORT).show();
                                            } else {
                                                Toast.makeText(OnlyMeFragment.this.getActivity(), generalClass.getMsg(), Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });
                                }


                                @Override
                                public void onFailure(String msg) {

                                }
                            },jsonObject.toString());
                }else {
                    Toast.makeText(OnlyMeFragment.this.getActivity(), "请填写信息", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initview() {

        tabList = view.findViewById(R.id.tab_list);
        
        lila1 = view.findViewById(R.id.lila1);
        mostEducation = view.findViewById(R.id.mostEducation);
        education = view.findViewById(R.id.education);
        address = view.findViewById(R.id.address);
        experience = view.findViewById(R.id.experience);
        individualResume = view.findViewById(R.id.individualResume);
        money = view.findViewById(R.id.money);
        positionId = view.findViewById(R.id.positionId);
        submit = view.findViewById(R.id.submit);
        lila2 = view.findViewById(R.id.lila2);
        mostEducation2 = view.findViewById(R.id.mostEducation2);
        education2 = view.findViewById(R.id.education2);
        address2 = view.findViewById(R.id.address2);
        experience2 = view.findViewById(R.id.experience2);
        individualResume2 = view.findViewById(R.id.individualResume2);
        money2 = view.findViewById(R.id.money2);
        positionId2 = view.findViewById(R.id.positionId2);
        lila3 = view.findViewById(R.id.lila3);
        mostEducation3 = view.findViewById(R.id.mostEducation3);
        education3 = view.findViewById(R.id.education3);
        address3 = view.findViewById(R.id.address3);
        experience3 = view.findViewById(R.id.experience3);
        individualResume3 = view.findViewById(R.id.individualResume3);
        money3 = view.findViewById(R.id.money3);
        positionId3 = view.findViewById(R.id.positionId3);
        submit3 = view.findViewById(R.id.submit3);

    }
}